package com.darsystems.foghourz.server;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.darsystems.foghourz.client.DailyWork;
import com.darsystems.foghourz.client.FBResponse;
import com.darsystems.foghourz.client.FogBugzService;
import com.darsystems.foghourz.client.UserWorkInfo;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class FogBugzServiceImpl extends RemoteServiceServlet implements
		FogBugzService {

	private FBServiceAPI fbService = new FBServiceAPI();
	private final static DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd");
	public String login(String userName, String password) {
		return fbService.getToken(userName, password);
	}
	
	public FBResponse executeCommand(String token, String command, String args)
	{
		return fbService.executeCommand(token, command, args);
	}
	
	public DailyWork [] getDailyWork(String token, Date end, int previousDays)
	{
		String args = formatStartEndArgs(end, previousDays);
		
		FBResponseInternal response = fbService.executeCommandInternal(token, "listIntervals", args);
		if(!response.isOK())
		{
			return null;
		}
		
		try {
			return Interval.getDailyWorkSummary(response.getResponseDoc());
			
		} catch (Exception e) {
			return null;
		}
		
	}

	private String formatStartEndArgs(Date end, int previousDays) {
		String endDateStr = dtFormat.format(end) + "T23:59:00Z";
		Calendar c = Calendar.getInstance();
		c.setTime(end);
		c.add(Calendar.DAY_OF_YEAR, -previousDays);
		String startDateStr = dtFormat.format(c.getTime());
		
		String args = String.format("dtStart=%s&dtEnd=%s", startDateStr, endDateStr);
		return args;
	}
	
	public FBResponse stopWork(String token)
	{
		FBResponseInternal response = fbService.executeCommandInternal(token, "stopWork", "");
		return response.getBaseResponse();
	}

	@Override
	public UserWorkInfo getUserWorkInfo(String token) {
		FBResponseInternal response = fbService.executeCommandInternal(token, "listWorkingSchedule", "");
		return ResponseParser.parseUserWorkInfo(response.getResponseDoc());
	}
	
}
